//
//  BaseSignUpViewController.m
//  OTOClient
//
//  Created by Suny on 15/3/16.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "BaseSignUpViewController.h"
#import "MMProgressHUD.h"
#import "IZValueSelectorView.h"
#import "ImageSampleCroperViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>

#define kTextFieldHeightDefault 40


#define ORIGINAL_MAX_WIDTH 640.0f

@interface RCTextField : UITextField
@end

@interface BaseSignUpViewController ()<UITextFieldDelegate, IZValueSelectorViewDataSource, UIActionSheetDelegate ,
UINavigationControllerDelegate, UIImagePickerControllerDelegate,ImageSampleCroperDelegate>

@property (nonatomic,weak)UIView *inputBackground;
@property (nonatomic,weak)IZValueSelectorView *ageSelectorView;


@end

@implementation RCTextField
- (CGRect)textRectForBounds:(CGRect)bounds 
{
	return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
					  bounds.size.width - 20, bounds.size.height - 16);
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
	return [self textRectForBounds:bounds];
}
@end


@implementation BaseSignUpViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		// Custom initialization
	}
	return self;
}

-(void)cancelSignup 
{
	[self invalidateFirstResponders];
	[self back];
}


/**
 *	@brief	键盘出现
 *
 *	@param 	aNotification 	参数
 */
- (void)keyboardWillShow:(NSNotification *)aNotification
{
	[UIView animateWithDuration:0.25 animations:^{
		
		self.view.frame = CGRectMake(0.f, -35.f, self.view.frame.size.width, self.view.frame.size.height);
		
	}completion:nil] ;
	
}

/**
 *	@brief	键盘消失
 *
 *	@param 	aNotification 	参数
 */
- (void)keyboardWillHide:(NSNotification *)aNotification 
{
	[UIView animateWithDuration:0.25 animations:^{
		self.view.frame = CGRectMake(0.f, 0.f, self.view.frame.size.width, self.view.frame.size.height);
	}completion:nil];
	
}

-(void)configureNavigationBar 
{
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"取消", nil)
																	 style:UIBarButtonItemStylePlain target:self
																	action:@selector(cancelSignup)];
	cancelButton.tintColor = [UIColor clearColor];
	self.navigationItem.leftBarButtonItem = cancelButton;
	self.navigationController.navigationBar.backgroundColor = [UIColor redColor];
}

- (void)viewDidLoad 
{
	[super viewDidLoad];

	
	UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:self.view.bounds];
	backgroundView.image = [UIImage imageNamed:@"login_view_background"];
	[self.view addSubview:backgroundView];
	
	
	UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
	title.font = [UIFont systemFontOfSize:18];
	title.backgroundColor = [UIColor clearColor];
	title.textColor = [UIColor clearColor];
	title.textAlignment = NSTextAlignmentCenter;
	title.text = NSLocalizedString(@"注册", nil);
	self.navigationItem.titleView = title;
	[self.view setBackgroundColor:RGBCOLOR(230, 230, 230)];
	[self configureNavigationBar];
	[self configViews];

}

-(void)configViews
{
	
	UIView *signupFormContainer = [[UIView alloc] initWithFrame:CGRectZero];

    [signupFormContainer setFrame:CGRectMake(10, 50, self.view.width - 2 * 10, 0)];

	
	CGFloat w = 70; 
	CGFloat h = w;
	CGFloat x = 0;
	CGFloat y = 0;
	UIImageView *portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
	[portraitImageView.layer setCornerRadius:(portraitImageView.frame.size.height/2)];
	[portraitImageView.layer setMasksToBounds:YES];
	[portraitImageView setContentMode:UIViewContentModeScaleAspectFill];
	[portraitImageView setClipsToBounds:YES];
	portraitImageView.layer.shadowColor = [UIColor blackColor].CGColor;
	portraitImageView.layer.shadowOffset = CGSizeMake(4, 4);
	portraitImageView.layer.shadowOpacity = 0.5;
	portraitImageView.layer.shadowRadius = 2.0;
	portraitImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
	portraitImageView.layer.borderWidth = 2.0f;
	portraitImageView.userInteractionEnabled = YES;
	portraitImageView.backgroundColor = [UIColor blackColor];
	portraitImageView.image = [UIImage imageNamed:@"uv_default_avatar"];
	UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleClickHeadBtn:)];
	[portraitImageView addGestureRecognizer:portraitTap];
	
    portraitImageView.centerX = (CGFloat) (signupFormContainer.width/2.0);

    portraitImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
	[signupFormContainer addSubview:portraitImageView];
	
	_headerImageView = portraitImageView;
	
	
	UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _headerImageView.bottom + 20, 100, 20)];
	tipLabel.text = @"添加头像";
	tipLabel.backgroundColor = [UIColor clearColor];
	[tipLabel sizeToFit];
	tipLabel.font = [UIFont systemFontOfSize:16];
	[signupFormContainer addSubview:tipLabel];
	tipLabel.centerX = signupFormContainer.width/2;
	
	
	UIImage *inputBackgroundImage = [[UIImage imageNamed:@"input_bg"] 
									 resizableImageWithCapInsets:UIEdgeInsetsMake(5.f, 5.f, 5.f, 5.f)];
	UIImageView *inputBackground = [[UIImageView alloc] initWithFrame:CGRectMake(0,
                                                                                 tipLabel.bottom + 10,
                                                                                 signupFormContainer.width,
                                                                                 4* kTextFieldHeightDefault)];
	[inputBackground setImage:inputBackgroundImage];
	inputBackground.userInteractionEnabled = YES;
	[signupFormContainer addSubview:inputBackground];
	
	_inputBackground = inputBackground;
	
	
//	RCTextField *firstNameField= [[RCTextField alloc] initWithFrame:CGRectMake(0, 0,signupFormContainer.width/2  , kTextFieldHeightDefault)];
//	firstNameField.tag = Tag_FirstNameTextField;
//	firstNameField.returnKeyType = UIReturnKeyNext;
//	firstNameField.delegate = self;
//	firstNameField.placeholder = NSLocalizedString(@"姓", nil);
//	firstNameField.keyboardType = UIKeyboardTypeEmailAddress;
//	firstNameField.backgroundColor = [UIColor clearColor];
//	firstNameField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//	[inputBackground addSubview:firstNameField];
//
//	UIView *verticleLine = [self verticleLineImageViewWithWidth:firstNameField.height];
//	verticleLine.centerX = firstNameField.right;
//	verticleLine.centerY = firstNameField.centerY;
//	[inputBackground addSubview:verticleLine];
//	
//	RCTextField *secondNameField= [[RCTextField alloc] initWithFrame:CGRectMake(firstNameField.right, 0,signupFormContainer.width/2  , kTextFieldHeightDefault)];
//	secondNameField.tag = Tag_SecondTextField;
//	secondNameField.returnKeyType = UIReturnKeyNext;
//	secondNameField.delegate = self;
//	secondNameField.placeholder = NSLocalizedString(@"名", nil);
//	secondNameField.backgroundColor = [UIColor clearColor];
//	secondNameField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//	[inputBackground addSubview:secondNameField];
//
//    UIImageView *lineView = [self horizontalLineImageViewWithWidth:inputBackground.width];
//    lineView.bottom = secondNameField.bottom;
//    [inputBackground addSubview:lineView];
	

	
	
	
	RCTextField *nikeNameField = [[RCTextField alloc] initWithFrame:CGRectMake(0, 0, signupFormContainer.width, kTextFieldHeightDefault)];
	nikeNameField.tag = Tag_NikeNameTextField;
	nikeNameField.returnKeyType = UIReturnKeyNext;
	nikeNameField.delegate = self;
	nikeNameField.placeholder = NSLocalizedString(@"输入昵称（4－12个字母）", nil);
	
	nikeNameField.backgroundColor = [UIColor clearColor];
	nikeNameField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[inputBackground addSubview:nikeNameField];

    UIImageView * lineView = [self horizontalLineImageViewWithWidth:inputBackground.width];
    lineView.bottom = nikeNameField.bottom;
    [inputBackground addSubview:lineView];

	RCTextField *emailField= [[RCTextField alloc] initWithFrame:CGRectMake(0, nikeNameField.bottom, signupFormContainer.width, kTextFieldHeightDefault)];
	emailField.tag = Tag_EmailTextField;
	emailField.returnKeyType = UIReturnKeyNext;
	emailField.delegate = self;
	emailField.placeholder = NSLocalizedString(@"输入邮箱", nil);
	emailField.keyboardType = UIKeyboardTypeEmailAddress;
	emailField.backgroundColor = [UIColor clearColor];
	emailField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	
	[inputBackground addSubview:emailField];
	
    lineView = [self horizontalLineImageViewWithWidth:inputBackground.width];
    lineView.bottom = emailField.bottom;
    [inputBackground addSubview:lineView];
	
	
	UIImageView *showOrHiddenPassword = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password_invisible"]];
	showOrHiddenPassword.highlightedImage = [UIImage imageNamed:@"password_visible"] ;
	UITapGestureRecognizer *showOrHiddenPasswordTap = [[UITapGestureRecognizer alloc] initWithTarget:self 
																							  action:@selector(showOrHiddenPasswordTap:)];
	[showOrHiddenPassword addGestureRecognizer:showOrHiddenPasswordTap];
	showOrHiddenPassword.userInteractionEnabled = YES;

    RCTextField *passwordField = [[RCTextField alloc] initWithFrame:CGRectMake(0, emailField.bottom, signupFormContainer.width - 10, kTextFieldHeightDefault)];
	passwordField.tag = Tag_TempPasswordTextField;
	passwordField.returnKeyType = UIReturnKeyDone;
	passwordField.secureTextEntry = YES;
	passwordField.delegate = self;
	passwordField.placeholder = NSLocalizedString(@"输入密码（6-16个字符，区分大小写）", nil);
	passwordField.backgroundColor = [UIColor clearColor];
    passwordField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [inputBackground addSubview:passwordField];
	passwordField.rightView = showOrHiddenPassword;
	passwordField.rightViewMode = UITextFieldViewModeAlways;
	
    lineView = [self horizontalLineImageViewWithWidth:inputBackground.width];
    lineView.bottom = passwordField.bottom;
    [inputBackground addSubview:lineView];

	
	UIButton *sexFemalebutton = [UIButton buttonWithType:UIButtonTypeCustom];
	[sexFemalebutton addTarget:self action:@selector(handleClickSexBtn:) forControlEvents:UIControlEventTouchUpInside];
	sexFemalebutton.frame = CGRectMake(0, passwordField.bottom,signupFormContainer.width/2.0, kTextFieldHeightDefault);
	sexFemalebutton.tag = Tag_SexFemalnButton;
	[sexFemalebutton setImage:[UIImage imageNamed:@"2_1_female_icon_grey"] forState:UIControlStateNormal];
	[sexFemalebutton setImage:[UIImage imageNamed:@"2_1_female_icon_selected"]
					 forState:UIControlStateSelected];
	[sexFemalebutton setTitle:@"女" forState:UIControlStateNormal];
	sexFemalebutton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[inputBackground addSubview:sexFemalebutton];
	sexFemalebutton.selected = YES;

    UIButton *sexMalebutton = [UIButton buttonWithType:UIButtonTypeCustom];
	[sexMalebutton addTarget:self action:@selector(handleClickSexBtn:) forControlEvents:UIControlEventTouchUpInside];
    sexMalebutton.frame = CGRectMake(sexFemalebutton.right, passwordField.bottom,signupFormContainer.width/2.0, kTextFieldHeightDefault);
    sexMalebutton.tag = Tag_SexMaleButton;
    [sexMalebutton setImage:[UIImage imageNamed:@"2_1_male_icon_grey.png"] forState:UIControlStateNormal];
    [sexMalebutton setImage:[UIImage imageNamed:@"2_1_male_icon_selected.png"]
            forState:UIControlStateSelected];
	[sexMalebutton setTitle:@"男" forState:UIControlStateNormal];
    sexMalebutton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[inputBackground addSubview:sexMalebutton];


	UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, inputBackground.bottom + 20, 80, 30)];
	label.backgroundColor = [UIColor clearColor];
	label.text = @"年龄";
	label.textColor = [UIColor whiteColor];
	label.font = [UIFont systemFontOfSize:24];
	[label sizeToFit];
	
	[signupFormContainer addSubview:label];
	
	IZValueSelectorView *ageValueSelectorView = [[IZValueSelectorView alloc] initWithFrame:CGRectMake(label.right + 10, 
																									  inputBackground.bottom + 20,
																									  inputBackground.width - label.right - 10, 30)];
	
	ageValueSelectorView.layer.cornerRadius = 4;
	ageValueSelectorView.backgroundColor = [UIColor whiteColor];
	ageValueSelectorView.dataSource = self;
	ageValueSelectorView.delegate = self;
	ageValueSelectorView.shouldBeTransparent = YES;
	ageValueSelectorView.horizontalScrolling = YES;
	
	//You can toggle Debug mode on selectors to see the layout
	ageValueSelectorView.debugEnabled = NO;
	
	[signupFormContainer addSubview:ageValueSelectorView];
	_ageSelectorView = ageValueSelectorView;
	
	
	UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [submitButton setFrame:CGRectMake(0, ageValueSelectorView.bottom + 20,signupFormContainer.width , kTextFieldHeightDefault)];
    [submitButton addTarget:self action:@selector(handleSignup:) forControlEvents:UIControlEventTouchUpInside];
	UIImage *buttonImage = [[UIImage imageNamed:@"regist_view_reg_btn_bg.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(7.f, 7.f, 7.f, 7.f)];
	[submitButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
	[submitButton setTitle:NSLocalizedString(@"同意并注册", nil) forState:UIControlStateNormal];
	[submitButton setTitleColor:HEXCOLOR(0x585858) forState:UIControlStateNormal];
	submitButton.titleLabel.font = [UIFont systemFontOfSize:18.f];
    [signupFormContainer addSubview:submitButton];
	_signUpButton = submitButton;
	[self.view addSubview:signupFormContainer];


    [signupFormContainer setFrame:CGRectMake(10, 50, self.view.width - 2 * 10, submitButton.bottom + 20)];

	_signupFormContainer = signupFormContainer;
}

- (UIImageView *)horizontalLineImageViewWithWidth:(CGFloat)width
{
    UIImage *seperatorImage = [[UIImage imageNamed:@"split_line"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
    UIImageView *seperator = [[UIImageView alloc] initWithImage:seperatorImage];
    [seperator setFrame:CGRectMake(2, 0,width - 2*2, 1)];

    return seperator;
}

- (UIImageView *)verticleLineImageViewWithWidth:(CGFloat)height
{
	UIImage *seperatorImage = [[UIImage imageNamed:@"split_line"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
	UIImageView *seperator = [[UIImageView alloc] initWithImage:seperatorImage];
	[seperator setFrame:CGRectMake(0, 0,1, height)];
	
	return seperator;
}

- (void)showOrHiddenPasswordTap:(UITapGestureRecognizer *)tapGesture
{
	UIImageView *showOrHiddenPassword = (UIImageView *)tapGesture.view;
	showOrHiddenPassword.highlighted = !showOrHiddenPassword.highlighted;
	
	UITextField *passwordTextField = [self textFieldWithTag:Tag_TempPasswordTextField];
	passwordTextField.secureTextEntry = !showOrHiddenPassword.highlighted ;
}

- (void)handleClickHeadBtn:(UITapGestureRecognizer *)tapGesture
{
	UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
															 delegate:self
													cancelButtonTitle:@"取消"
											   destructiveButtonTitle:nil
													otherButtonTitles:@"拍照", @"从相册中选取", nil];
	[choiceSheet showInView:self.view];

}

- (void)handleClickSexBtn:(UIButton *)handleClickSexBtn
{

}

- (void)handleSignup:(id)sender
{
	if ([self checkValidityTextField]) 
	{
		[self registToServer];
	}
}

- (BOOL)checkValidityTextField
{
	return YES;
}

#pragma mark - UITextFieldDelegate Method

- (void)textFieldDidBeginEditing:(UITextField *)textField{
	
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
	
	switch (textField.tag) {
			
		case Tag_EmailTextField:
		{
			if ([textField text] != nil && [[textField text] length]!= 0) {
				
				if (![self isValidateEmail:textField.text]) {
					
					[self alertTitle:@"提示" message:@"邮箱格式不正确" delegate:nil cancelBtn:@"取消" otherBtnName:nil];
					return;
				}
			}
		}
			break;
		case Tag_TempPasswordTextField:
		{
			if ([textField text] != nil && [[textField text] length]!= 0) {
				
				if ([[textField text] length] < 6) {
					
					[self alertTitle:@"提示" message:@"请输入6－16位的密码！" delegate:nil cancelBtn:@"取消" otherBtnName:nil];
					return;
				}
				else if ([[textField text] length] >16)
				{
					[self alertTitle:@"提示" message:@"请输入6－16位的密码！" delegate:nil cancelBtn:@"取消" otherBtnName:nil];
					textField.text = [textField.text substringToIndex:16];
					return;
				}
			}
		}
			break;
		default:
			break;
	}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	
	[textField resignFirstResponder];
	
	return YES;
}

#pragma mark - touchMethod
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	
	[super touchesBegan:touches withEvent:event];
	
	[self invalidateFirstResponders];
}

#pragma mark - PrivateMethod
- (void)invalidateFirstResponders
{
	NSArray *subviews = self.inputBackground.subviews;
	for (UIView *view in subviews)
	{
		if ([view isKindOfClass: [UITextField class]])
		{
			UITextField *textField = (UITextField *)view;
			[textField resignFirstResponder];
		}
	}
}


-(UILabel *)labelWithFrame:(CGRect)frame withTitle:(NSString *)title titleFontSize:(UIFont *)font textColor:(UIColor *)color backgroundColor:(UIColor *)bgColor alignment:(NSTextAlignment)textAlignment{
	
	UILabel *label = [[UILabel alloc] initWithFrame:frame];
	label.text = title;
	label.font = font;
	label.textColor = color;
	label.backgroundColor = bgColor;
	label.textAlignment = textAlignment;
	return label;
	
}

-(UIAlertView *)alertTitle:(NSString *)title message:(NSString *)msg delegate:(id)aDeleagte cancelBtn:(NSString *)cancelName otherBtnName:(NSString *)otherbuttonName{
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:aDeleagte cancelButtonTitle:cancelName otherButtonTitles:otherbuttonName, nil];
	[alert show];
	return alert;
}

//利用正则表达式验证邮箱的合法性
-(BOOL)isValidateEmail:(NSString *)email 
{
	
	NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
	NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
	return [emailTest evaluateWithObject:email];
	
}

-(void)registToServer
{

	[self showProgressHUDWithMessage:@"正在提交注册……"];
}

- (void)registSucceed:(BaseResponse *)response
{

	[self showProgressHUDWithMessage:response.desc];

	[self cancelSignup];
}


- (void)registFaild:(BaseResponse *)response

{

	[self showErrorMessage:response.desc];

}


- (UITextField *)textFieldWithTag:(NSInteger)tag
{
	UIView *view = [self.view viewWithTag:tag];
	if ([view isKindOfClass:[UITextField class]])
	{
		return (UITextField *)view;
	}
	else
	{
		return nil;
	}
}




#pragma IZValueSelector dataSource
- (NSInteger)numberOfRowsInSelector:(IZValueSelectorView *)valueSelector 
{
	return 100;
}



//ONLY ONE OF THESE WILL GET CALLED (DEPENDING ON the horizontalScrolling property Value)
- (CGFloat)rowHeightInSelector:(IZValueSelectorView *)valueSelector 
{
	return 70.0;
}

- (CGFloat)rowWidthInSelector:(IZValueSelectorView *)valueSelector 
{
	return 70.0;
}


- (UIView *)selector:(IZValueSelectorView *)valueSelector viewForRowAtIndex:(NSInteger)index {
	UILabel * label = nil;
		
	label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 70, self.ageSelectorView.frame.size.height)];

	label.text = [NSString stringWithFormat:@"%ld",(long)index];
	label.textAlignment =  NSTextAlignmentCenter;
	label.backgroundColor = [UIColor clearColor];
	return label;
}

- (CGRect)rectForSelectionInSelector:(IZValueSelectorView *)valueSelector {
	//Just return a rect in which you want the selector image to appear
	//Use the IZValueSelector coordinates
	//Basically the x will be 0
	//y will be the origin of your image
	//width and height will be the same as in your selector image
		
	return CGRectMake(self.ageSelectorView.frame.size.width/2 - 35.0, 0.0, 70.0, 90.0);

	
}

#pragma IZValueSelector delegate
- (void)selector:(IZValueSelectorView *)valueSelector didSelectRowAtIndex:(NSInteger)index {
	NSLog(@"Selected index %ld",(long)index);
}




#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		// 拍照
		if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
			UIImagePickerController *controller = [[UIImagePickerController alloc] init];
			controller.sourceType = UIImagePickerControllerSourceTypeCamera;
			if ([self isFrontCameraAvailable]) {
				controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
			}
			NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
			[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
			controller.mediaTypes = mediaTypes;
			controller.delegate = self;
			[self presentViewController:controller
							   animated:YES
							 completion:^(void){
								 NSLog(@"Picker View Controller is presented");
							 }];
		}
		
	} else if (buttonIndex == 1) {
		// 从相册中选取
		if ([self isPhotoLibraryAvailable]) {
			UIImagePickerController *controller = [[UIImagePickerController alloc] init];
			controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
			[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
			controller.mediaTypes = mediaTypes;
			controller.delegate = self;
			[self presentViewController:controller
							   animated:YES
							 completion:^(void){
								 NSLog(@"Picker View Controller is presented");
							 }];
		}
	}
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{
	[picker dismissViewControllerAnimated:YES completion:^() {
		UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
		portraitImg = [self imageByScalingToMaxSize:portraitImg];
		// 裁剪
		ImageSampleCroperViewController *imgEditorVC = [[ImageSampleCroperViewController alloc] initWithImage:portraitImg 
																									cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width)
																							  limitScaleRatio:3.0];
		imgEditorVC.delegate = self;
		[self presentViewController:imgEditorVC animated:YES completion:^{
			// TO DO
		}];
	}];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissViewControllerAnimated:YES completion:^(){
	}];
}





#pragma mark camera utility
- (BOOL) isCameraAvailable{
	return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
	return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
	return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
	return [UIImagePickerController isSourceTypeAvailable:
			UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
	return [self
			cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
	return [self
			cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
	__block BOOL result = NO;
	if ([paramMediaType length] == 0) {
		return NO;
	}
	NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
	[availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
		NSString *mediaType = (NSString *)obj;
		if ([mediaType isEqualToString:paramMediaType]){
			result = YES;
			*stop= YES;
		}
	}];
	return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
	if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
	CGFloat btWidth = 0.0f;
	CGFloat btHeight = 0.0f;
	if (sourceImage.size.width > sourceImage.size.height) {
		btHeight = ORIGINAL_MAX_WIDTH;
		btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
	} else {
		btWidth = ORIGINAL_MAX_WIDTH;
		btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
	}
	CGSize targetSize = CGSizeMake(btWidth, btHeight);
	return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize
{
	UIImage *newImage = nil;
	CGSize imageSize = sourceImage.size;
	CGFloat width = imageSize.width;
	CGFloat height = imageSize.height;
	CGFloat targetWidth = targetSize.width;
	CGFloat targetHeight = targetSize.height;
	CGFloat scaleFactor = 0.0;
	CGFloat scaledWidth = targetWidth;
	CGFloat scaledHeight = targetHeight;
	CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
	if (CGSizeEqualToSize(imageSize, targetSize) == NO)
	{
		CGFloat widthFactor = targetWidth / width;
		CGFloat heightFactor = targetHeight / height;
		
		if (widthFactor > heightFactor)
			scaleFactor = widthFactor; // scale to fit height
		else
			scaleFactor = heightFactor; // scale to fit width
		scaledWidth  = width * scaleFactor;
		scaledHeight = height * scaleFactor;
		
		// center the image
		if (widthFactor > heightFactor)
		{
			thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
		}
		else
			if (widthFactor < heightFactor)
			{
				thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
			}
	}
	UIGraphicsBeginImageContext(targetSize); // this will crop
	CGRect thumbnailRect = CGRectZero;
	thumbnailRect.origin = thumbnailPoint;
	thumbnailRect.size.width  = scaledWidth;
	thumbnailRect.size.height = scaledHeight;
	
	[sourceImage drawInRect:thumbnailRect];
	
	newImage = UIGraphicsGetImageFromCurrentImageContext();
	if(newImage == nil) NSLog(@"could not scale image");
	
	//pop the context to get back to the default
	UIGraphicsEndImageContext();
	return newImage;
}


#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
	
}


#pragma mark- ImageSampleCropperDelegate
- (void)imageCropper:(ImageSampleCroperViewController *)cropperViewController didFinished:(UIImage *)editedImage 
{
	[self.headerImageView setImage:editedImage];
	[cropperViewController dismissViewControllerAnimated:YES completion:^{
		// TO DO
	}];
}

- (void)imageCropperDidCancel:(ImageSampleCroperViewController *)cropperViewController
{
	[cropperViewController dismissViewControllerAnimated:YES completion:^{
	}];
}


@end